package com.weilele.mvvm.utils.`object`

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Configuration
import android.content.res.Resources
import androidx.core.content.ContextCompat
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.app
import kotlin.math.min

/**
 * 描述：屏幕适配,app的尺寸不做处理，不做适配，只对activity适配
 * 可以根据需要来觉得是否适配
 */
object ScreenAdaptationObj {
    private val appDm = app.resources.displayMetrics
    private val customDensity = appDm.density
    private val customFontScaleDensity =
        appDm.scaledDensity / if (MvvmConf.ENABLE_SYSTEM_FONT_SCALE) 1f else app.resources.configuration.fontScale

    //屏幕适配适配后的密度因子
    val density by lazy {
        min(
            appDm.widthPixels.toFloat(),
            appDm.heightPixels.toFloat()
        ) / MvvmConf.SCREEN_ADAPTATION_UI_DP_WIDTH
    }

    //屏幕适配后的字体缩放因子
    //因为适配之后的字体总是偏大，所以设置0.96使他小一点
    val scaledDensity by lazy { density * (customFontScaleDensity / customDensity) * 0.96f }

    //屏幕适配后的Dpi
    val densityDpi by lazy { (160 * density).toInt() }

    fun setCustomDensity(activity: Activity?) {
        setCustomDensity(activity?.resources)
    }

    fun setCustomDensity(resources: Resources?) {
        resources ?: return
        val activityDm = resources.displayMetrics
        activityDm.density = density
        activityDm.scaledDensity = scaledDensity
        activityDm.densityDpi = densityDpi
    }
}